package com.moliku.insurance.common.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 七分
 * @version 1.0
 * @date 2021/3/19 9:01
 * @effect
 */
public class AXAHttpUtils {

    /**
     * 安盛请求
     *
     * @param data     数据
     * @param username 用户名
     * @param password 密码
     * @param url      请求地址
     * @return 响应体
     */
    public static String synPdmData(String data, String username, String password, String url) {

        HttpClient httpClient = new HttpClient();
        UsernamePasswordCredentials creds = null;
        //需要验证
        try {
            creds = new UsernamePasswordCredentials(username, password);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        httpClient.getState().setCredentials(AuthScope.ANY, creds);
        //设置http头
        List<Header> headers = new ArrayList<Header>();
        headers.add(new Header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));
        httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);

        PostMethod method = new PostMethod(url);
        RequestEntity requestEntity = new StringRequestEntity(data);
        method.setDoAuthentication(true);
        method.setRequestEntity(requestEntity);
        try {
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("Method failed code=" + statusCode + ": " + method.getStatusLine());
                return null;
            } else {
                return new String(method.getResponseBody(), "GBK");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return null;
    }
}
